import { useEffect, useState } from "react";
import { Button, Upload, Modal, message } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import { SelectStaff, SelectTag } from "@/components/func";
import { excelUpload } from "@/assets/js/networkRequest/method";
import querystring from "querystring";

interface UploadComProps {
  visible: boolean;
  setVisible: any;
}

let staffFlag: boolean = true;
const UploadCom = ({ visible, setVisible }: UploadComProps) => {
  const [tagVisible, setTagVisible] = useState(false);
  const [fileList, setFileList]: any = useState([]);
  const [customerTag, setCustomerTag] = useState([]);
  const [staff, setStaff]: any = useState([]);

  const props = {
    accept: ".xlsx",
    onRemove: (file: any) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file: any) => {
      setFileList([file]);
      return false;
    },
    fileList,
  };

  // 初始化数据
  const initData = () => {
    staffFlag = false;
    setFileList([]);
    setCustomerTag([]);
    setStaff([]);
    setVisible(false);
  };

  useEffect(() => {
    staffFlag = visible;
  });

  return (
    <div>
      <h2 className="dialog-title">上传表格</h2>

      <div>
        <div className="bg-blue-acd7ff bg-opacity-20 text-xs leading-5 text-grey-600 px-20 py-6">
          请下载模板后输入手机号上传，可批量复制手机号至模板内，若输入内容有重复手机号或空行将会自动过滤
        </div>
        <span className="inline-block text-xs mt-12 text-grey-800">
          点击下载
          <a
            className="text-blue-default cursor-pointer"
            href="http://192.168.15.49:7001/public/批量添加好友导入名单.xlsx"
            download>
            Excel模板
          </a>
        </span>

        {/* 选择表格 */}
        <div className="flex mt-16 items-center">
          <span className="title-item text-right mr-16 w-80">
            <span className="text-red-defalut relative top-4 text-lg">*</span> 选择表格:
          </span>
          <div className="flex-1">
            <Upload {...props}>
              {fileList.length ? (
                <Button
                  icon={<i className="iconfont icon-xls1 mr-5" />}
                  className="flex items-center">
                  <span className="max-w-60 overflow-hidden overflow-ellipsis break-all whitespace-nowrap">
                    {fileList[0].name.split(".")[0]}
                  </span>
                  <span>{`.${fileList[0].name.split(".")[1]}`}</span>
                </Button>
              ) : (
                <Button icon={<UploadOutlined />}>上传表格</Button>
              )}
            </Upload>
          </div>
        </div>

        {/* 选择员工 */}
        <div className="flex mt-16 items-start">
          <span className="title-item text-right mr-16 w-80 mt-6">
            <span className="text-red-defalut relative top-4 text-lg">*</span> 选择员工:
          </span>
          <div className="flex-1">
            {staffFlag && (
              <SelectStaff
                id="upload-xlsx"
                multiple={true}
                placeholder="选择员工"
                setStaff={setStaff}
              />
            )}
            <p className="text-xs text-grey-600 leading-5 mt-8">
              表格内手机号将平均分配给选择的员工，分配完成后员工会在企业微信「微伴提醒」收到添加好友的任务，需要员工手动添加
            </p>
          </div>
        </div>

        {/* 客户标签 */}
        <div className="flex mt-16 items-start">
          <span className="title-item text-right mr-16 w-80">客户标签:</span>
          <div className="flex-1">
            <div className="flex items-center flex-wrap">
              {/* 添加标签 */}

              <div
                className="h-28 flex items-center justify-center cursor-pointer select-none text-blue-default rounded-sm mr-12 mb-8 border-1 border-blue-default border-solid px-6"
                onClick={() => {
                  setTagVisible(true);
                }}>
                + 添加标签
              </div>

              {/* 选择的标签 */}
              {customerTag.map((item: any, index: number) => {
                return (
                  <div
                    className="h-28 flex items-center justify-center cursor-pointer select-none text-grey-600 rounded-sm mr-12 mb-8 border-1 border-grey-300 border-solid px-6"
                    key={item.id}>
                    {item.name || item.stage_name}
                    <span
                      className="cursor-pointer ml-4"
                      onClick={() => {
                        setCustomerTag(
                          customerTag.filter((TagItem: any) => TagItem.id !== item.id)
                        );
                      }}>
                      <i className="iconfont icon-chuyidong text-grey-300 text-xs"></i>
                    </span>
                  </div>
                );
              })}
            </div>
            <p className="text-xs text-grey-600 leading-5">
              设置标签后，表格内添加成功的客户将会被自动添加选择的标签
            </p>
          </div>
        </div>
      </div>

      <div className="btn-wrap">
        <div className="left"></div>
        <div className="right">
          <Button
            onClick={() => {
              initData();
            }}>
            取消
          </Button>
          <Button
            type="primary"
            onClick={async () => {
              if (!staff.length || !fileList.length) {
                message.warn("请选择员工和表格");
                return;
              }
              const data: any = new FormData();
              data.append("file", fileList[0]);
              let query: string = querystring.stringify({
                userid: staff.map((item: any) => item.userid),
                tagid: customerTag.map((item: any) => item.ext_id),
              });

              let res: any = await excelUpload({
                query: `?&${query}`,
                fs: data,
                headers: {
                  "Content-Type": "application/x-www-form-urlencoded",
                },
              });
              if (res.code === 200) {
                message.warn("上传成功");
                initData();
              }
            }}>
            保存
          </Button>
        </div>
      </div>

      <Modal
        closable={false}
        maskClosable={false}
        visible={tagVisible}
        width={634}
        footer={null}
        onCancel={() => {
          setVisible(false);
        }}>
        <SelectTag
          setVisible={setTagVisible}
          customerTag={customerTag}
          setCustomerTag={setCustomerTag}
        />
      </Modal>
    </div>
  );
};

export default UploadCom;
